This code does not compile, but i couldnot find what is wrong with the code. I think shared_ptr matters.
#include <memory>
#include <iostream>
using namespace std;
class A {
public:
virtual const void test() const = 0;
~A() { }
};
class AImpl : public A {
public:
const void test() const {
std::cout << "AImpl.test" << std::endl;
}
};
class B {
public:
B() { }
~B() {
}
shared_ptr<A> CreateA() {
a_ = make_shared<AImpl>(new AImpl());
return a_;
}
private:
shared_ptr<A> a_;
};
int main() {
B *b = new B();
shared_ptr<A> p = b->CreateA();
if (b) {
delete b;
b = NULL;
}
}
ou are using make_shared incorrectly. You dont need to use new in make_shared, it defeats the whole purpose of this function template.
This function is typically used to replace the construction std::shared_ptr(new T(args...)) of a shared pointer from the raw pointer returned by a call to new. In contrast to that expression, std::make_shared typically allocates memory for the T object and for the std::shared_ptr's control block with a single memory allocation (this is a non-binding requirement in the Standard), where std::shared_ptr(new T(args...)) performs at least two memory allocations.
a_ = make_shared<AImpl>(); // correct
//a_ = make_shared<AImpl>(new AImpl()); // not correct
반응형
'프로그래밍(Programming) > c++, 11, 14 , 17, 20' 카테고리의 다른 글
When does a std::vector enlarge itself when we push_back elements? (0) | 2023.03.06 |
---|---|
Type Conversion - compile time (Dynamic Cast 과 유사) (0) | 2022.10.17 |
C++ 락(std::lock, std::unique_lock, std::lock_guard, condition_variable...) (0) | 2022.08.11 |
C++ "Virtual functions but no virtual destructors" (0) | 2022.04.27 |
error C4596: illegal qualified name in member (0) | 2022.03.03 |