You have
two pointers in your code:
Line 2:
const char* text;
Line 14:
A *a = ...
You assign a dynamically-allocated value to
a
, and properly clean up.
But you assign a non-dynamically-allocated, global string literal constant to
text
...and then try to delete[] it. The runtime properly barfs.
If you intend to accept string literals as assignment as delete-able resources, you must make a proper copy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <cstring>
char* clone( const char* s )
{
char* r = new char[ std::strlen( s ) + 1 ];
return r ? std::strcpy( r, s ) : NULL;
}
class A {
const char *text;
public:
A(const char *text) : text(text) {}
virtual ~A() {
delete[] text;
}
};
int main() {
A *a = new A(clone("Hello world"));
delete a;
return 0;
}
|
That said, you would do better to avoid dealing with this stuff yourself. Use std::string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <memory>
#include <string>
class A {
std::string text;
public:
A(const std::string& text) : text(text) {}
virtual ~A() {
}
};
int main() {
std::shared_ptr<A> a = std::make_shared<A>("Hello world");
return 0;
}
|
Hope this helps.
[edit]
Sorry, the std::string means you don't have to clean up after the text, and can treat it like normal.
The std::shared_ptr means you get an object you can treat like a normal pointer-to-A, but you don't have to clean up yourself.
1 2 3 4 5
|
auto a = std::make_shared<A>("Hello world!");
...
a->do_something();
...
return 0;
|
Hope that helps better. :)
[edit 2]
Accidentally used std::strdup() and delete[] together ...which was dumb. Fixed.