I've been attempting to solve this problem for hours, because I can't get a pointer to delete itself so I created a text-based program for debugging. Why doesn't this work?
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class A {};
int main() {
vector<A> as;
std::auto_ptr<A> a(new A);
as.push_back(std::move(a));
return 0;
}
Considering the vector contains A objects, you want as.push_back(*a). You don't need std::move, the temporary *a is already moveable.
Related
Can someone explain why below piece of code is not working if I don't use explicitly std::pair with map insert :
#include <iostream>
#include <string>
#include <map>
#include <memory>
typedef std::shared_ptr<int>(*CreatorFunction)();
std::shared_ptr<int> test()
{
std::shared_ptr<int> p(new int);
return p;
}
int main()
{
std::map<int, CreatorFunction> tmap;
tmap.insert(1,test); //this doesn't work
tmap.insert(std::pair<int,CreatorFunction>(1,test)); //this works
return 0;
}
My understanding is in c++14 we don't need to use std::pair as insert function definition is changed to accept universal reference as indicated below :
template <class P> pair<iterator,bool> insert (P&& val);
There is no any overload in std::map::insert that takes two arguments you should use std::make_pair. See the snippet below
#include <iostream>
#include <string>
#include <map>
#include <memory>
#include <functional> // for std::function.
// typedef std::shared_ptr<int>(*CreatorFunction)();
typedef std::function<std::shared_ptr<int>()> CreatorFunction; // The c++ way.
// Take a look at this function. std::shared_ptr<int> will automatically destroy the int* and might result in undefined.
std::shared_ptr<int> test()
{
std::shared_ptr<int> p(new int);
return p;
}
int main()
{
std::map<int, CreatorFunction> tmap;
tmap.insert(std::make_pair(1,test)); // edited this line
tmap.insert(std::pair<int,CreatorFunction>(1,test)); // this works
return 0;
}
I am learning about smart pointers and when trying to compile the following "stupid" code I get an error.
#include <memory>
#include <iostream>
class Test
{
std::string myString="dumm";
};
int main()
{
std::unique_ptr<Test> test(new Test());
std::cout<<test->myString<<std::endl;
return 0;
}
I just wanted to see, whether this works but I get :"Applying -> to std::unique_ptr instead of a pointer", which seems weird.
I am using c++ 11
Eit: The error is now fixed and I cancompile the above code. However, CLion still gives me "Cant apply -> to std::uniq_ptr"-stuff, which seems to be an error with the IDE
In a class the default visibility is private which makes the myString field invisible to the test object. Make it public:
#include <iostream>
#include <memory>
#include <string>
class Test {
public:
std::string myString = "dumm";
};
int main() {
std::unique_ptr<Test> test(new Test());
std::cout << test->myString;
}
Prefer std::make_unique to direct use of new if compiling for C++14 and later:
std::unique_ptr<Test> test = std::make_unique<Test>();
This function is not available in the C++11 standard which is what you are using.
I'm trying to use arrays with unique_ptr with no success.
What is the correct way to declare a unique_ptr of some size?
(size is some paramter).
unique_ptr<A[]> ptr = make_unique<A[]>(size);
Here's an example:
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <memory>
using namespace std;
class A {
string str;
public:
A(string _str): str(_str) {}
string getStr() {
return str;
}
};
int main()
{
unique_ptr<A[]> ptr = make_unique<A[]>(3);
}
This is not working, however, if I delete the constructor of A, it works.
I want the 3 to represent the size of the array, and not an argument to A's constructor, how do I make that happen?
This is not working, however, if I delete the constructor of A, it
works.
When you removed the user defined constructor, the compiler implicitly generates a default one. When you provide a user defined constructor, the compiler doesn't implicitly generate a default constructor.
std::make_unique<T[]> requires the use of default constructors...
So, provide one, and all should work well
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <memory>
using namespace std;
class A {
string str;
public:
A() = default;
A(string _str): str(_str) {}
string getStr() {
return str;
}
};
int main()
{
unique_ptr<A[]> ptr = make_unique<A[]>(3);
}
Here is my code
main.cpp
#include <iostream>
#include "header.h"
#include "source.cpp"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
int testarray[]={1,3,5,7};
mymatrix* first=new mymatrix(testarray,2,2);
return 0;
}
and header.h
using namespace std;
#include <iostream>
#include <string>
class mymatrix{
public:
int i;
int j;
int marray[];
mymatrix(int m[],int rows,int cols ) : marray(m),i(rows),j(cols)
{
cout<<"this is for testings ";
}
mymatrix()
{};
~mymatrix(){
// delete[] marray;
};
};
I get this error :Invalid use of non static data member mymatrix::i
what I wanna do is make a object of my
matrix class and pass an array
Convert it from
int marray[];
to
int *marray;
In addition, either use C paradigm or use C++ one but not the mixture.
Instead of
mymatrix* first=new mymatrix(testarray,2,2);
use
mymatrix first(testarray,2,2);
Let the compiler allocate and release the memory instead of you.
If you have no restriction about the C++ libraries that you use, consider std::vector library to manage your dynamic arrays.
Instad of managing memory out of the object, manage it inside the object specially inside constructor and destructor.
I've made a SSCE as best I can. My suspicion is that the shared pointers deconstruct (free) my objects before I ask for them in main. How can I prevent this without circumventing shared pointers altogether? This is in isolated problem in a program that otherwise is greatly helped by the use of shared_ptrs.
Test.h:
#ifndef TEST_H
#define TEST_H
#include <memory>
#include <iostream>
#include <vector>
class Test
{
public:
Test();
virtual ~Test();
static std::shared_ptr<Test> makeTestFrom(std::string l);
std::vector<std::shared_ptr<int>> reg_vec;
protected:
private:
};
#endif // TEST_H
Test.cpp
#include <memory>
#include <iostream>
#include <vector>
Test::Test():
reg_vec()
{
//ctor
}
Test::~Test()
{
//dtor
}
std::shared_ptr<Test> Test::makeTestFrom(std::string l)
{
std::shared_ptr<Test> sp(new Test());
std::shared_ptr<int> i(new int(3));
sp->reg_vec.push_back(i);
return sp;
}
main.cpp:
#include <memory>
#include <iostream>
#include <vector>
#include "include/Test.h"
using namespace std;
int main()
{
std::unique_ptr<Test> x(new Test());
x->makeTestFrom("loldoesntmatter");
std::cout << x->reg_vec[0] << std::endl;
return 0;
}
int main() {
std::unique_ptr<Test> x(new Test());
x->makeTestFrom("loldoesntmatter"); // you discarded the return
std::cout << x->reg_vec[0] << std::endl; // x->reg_vec is empty
return 0;
}
Also, too many shared pointers
You're making too many new objects. In main, you're looking for an int inside x->reg_vec, but makeTestFrom doesn't add anything to x, it creates a brand-new object and puts the integer inside that.
Besides that, you're abusing shared_ptr. In C++, avoid dynamic allocation when you can. int are cheaper to pass by value than with shared_ptr, so just use vector<int>. And Test objects can be created with automatic lifetime also.
Just because some other languages (i.e. Java) make everything a handle doesn't mean that's a good pattern for C++.