Reference not returning? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
My class has an array of objects, call it Foo. It is stored as Foo* m_Foos in the class. Say it has a value at [0], guaranteed, and Foo has a property called IsSetthat's just a bool or something.
void TryThis()
{
Foo returnValue;
GetValue(returnValue);
returnValue.IsSet = true;
if(m_Foo[0].IsSet != returnValue.IsSet)
{
// ERROR!!!!
}
}
void GetValue(Foo &container)
{
container = m_Foos[0];
}
Can anyone explain why m_Foo[0] =/= returnValue? Where is the error in my syntax?
I expect m_Foo[0] to be the same reference as returnValue, the same Foo in memory.

TryThis() is not modifying the Foo object that is stored in the m_Foos array.
GetValue() is assigning the Foo object from m_Foos[0] to another Foo object that is local to TryThis(). A copy is being made during that assigment. TryThis() is then modifying the copy, not the original.
If you want TryThis() to modify the original Foo object directly, you need to do something more like this instead:
void TryThis()
{
Foo &returnValue = GetValue();
returnValue.IsSet = true;
// m_Foo[0] is set true.
}
Foo& GetValue()
{
return m_Foos[0];
}
Or this:
void TryThis()
{
Foo *returnValue;
GetValue(returnValue);
returnValue->IsSet = true;
// m_Foo[0] is set true.
}
void GetValue(Foo* &container)
{
container = &m_Foos[0];
}

Related

Initializing an object as in a vector class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
So, I know a vector object can be declared and initialized like this:
// Nothing new here. I know <int> is a template
// and how to implement it:
vector <int> vect{ 10, 20, 30 };
I assume that the vector object has inside an array of values, and the functions of that class (like push_back() for example) manage it. I would like and have been trying to implement something like that in a class of my own, without success. Would be interesting being able to understand how it's done! Did many "experiments" but none worked.
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
public:
// Trying to accept the input values between
// brackets and putting them inside a temp array:
A_Class(int Input_Array[]) {}
};
int main()
{
// trying to create the object like in the vector class.
// Returns error "No instance of constructor matches the argument list":
A_Class My_Object{1,2,3}
return 0;
}
In a function parameter, int Input_Array[] is just syntax sugar for a decayed pointer int* Input_Array, which does not provide any information about any array that may be passed in to it.
For what you are attempting, you need to accept a std::initializer_list instead, eg:
#include <initializer_list>
#include <algorithm>
// Random named class:
class A_Class
{
private:
// A pointer for the type I want:
int *A_pointer_To_int;
// the number of values in the array:
size_t size;
public:
A_Class(std::initializer_list<int> Input_Values) {
size = Input_Values.size();
A_pointer_To_int = new int[size];
std::copy(Input_Values.begin(), Input_Values.end(), A_pointer_To_int);
}
~A_Class() {
delete[] A_pointer_To_int;
}
};
int main()
{
A_Class My_Object{1,2,3}; // works now
return 0;
}
Online Demo

using a shared_ptr object in constructor works but not in destructor [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I have a class where the construction is like:
class CLSS
{
public:
CLSS(const std::shared_ptr<someType>& pobj)
{
std::shared_ptr<someType> obj = pobj;
obj->somefunc("DDDD")
}
~CLSS()
{
}
};
which works with now problem. However when I put the same function of obj->info("DDDD") in the diconstructor, it returns error, that is:
...
~CLSS()
{
obj->info("DDDD")
}
....
---------------edit
I tried
class CLSS
{
public:
std::shared_ptr<someType> obj;
CLSS(const std::shared_ptr<someType>& pobj)
{
obj = pobj;
obj->somefunc("DDDD")
}
~CLSS()
{
}
};
but still does not compile, the errors are not very readble.
obj is a local variable in the constructor. It is destroyed when the constructor ends.
You need to declare it as a member of your class.

How avoid error on not evaluated code C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Apologies for the most ambiguous and bizarre title.
Suppose we have 2 classes A and B.
class B has interface hasSmth but class A has not.
How to make this code evaluate without compile errors?
class A {
//..implementation
int id() { return 1; }
};
class B {
//..implementation
int id() { return 2; }
bool hasSmth() { return true; }
};
int main()
{
auto obj = someFunction();//returns A or B
if (obj.id() == 1 || (obj.id() == 2 && obj.hasSmth())) {
...
}
}
If the function returns obj of type B, then we are good.
But if it returns obj of type A, compiler will complain about A not having hasSmth, regardless of that part of if never been evaluated.
Can someone give a workaround please?
Can someone give a workaround please?
Read the declaration of someFunction to see what it returns. In the case it doesn't return B, then don't write obj.hasSmth(). Problem solved.
Now, let's change the question a bit. Let's say that you want to make this work without knowing the return type. Perhaps because rather than main you may be actually writing a template that works with different types. There are several approaches, but function overloads are a simple one:
bool check([[maybe_unused]] const A&) {
return true;
}
bool check(const B& b) {
return b.hasSmth();
}
template<bool returnsA>
void foo() {
auto obj = someTemplate<returnsA>(); // returns A or B
if (check(obj)) {

How can I optimize function calls while setting the string values? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
In the below code snippet, from ReadFile() function I am calling SetParams() and Execute() multiple times.
Can I optimize each SetParams() and Execute() with single call?
bool SubscriptionRead::ReadFile()
{
IVerification* pReader = new FileReader();
std::wstring oemPathPublicKey(oemFolderPath)
, oemPathSessionKey(oemFolderPath)
, oemPathUserChoices(oemFolderPath);
oemPathPublicKey.append(PUBLIC_KEY_FILE);
oemPathSessionKey.append(SESSION_KEY_FILE);
oemPathUserChoices.append(USERCHOICES_FILE);
pReader->SetParams((wchar_t*)oemPathPublicKey.c_str(), L"file");
pReader->Execute();
pReader->SetParams((wchar_t*)oemPathSessionKey.c_str(), L"file");
pReader->Execute();
pReader->SetParams((wchar_t*)oemPathUserChoices.c_str(), L"file");
pReader->Execute();
return True;
}
void FileReader::SetParams(wchar_t* wszParams, wchar_t* wszParamType)
{
m_wszParamType = wszParamType;
m_wszParams = wszParams;
}
bool FileReader::Execute()
{
if (wcscmp(m_wszParamType, L"registry") == 0)
{
function1();
}
else
{
function2();
}
return true;
}
If your problem is calling the functions with different paras, in different lines, you can use std::ref as follows to iterate through the initializer_list of reference wrapper to the objects(i.e. std::wstring s), which reduces some typing:
#include <functional> // std::ref
#include <initializer_list> // std::initializer_list
bool SubscriptionRead::ReadFile()
{
IVerification* pReader = new FileReader();
// .... other code
for(auto strKey: {std::ref(oemPathPublicKey), std::ref(oemPathSessionKey), std::ref(oemPathSessionKey)})
{
pReader->SetParams((wchar_t*)strKey.c_str(), L"file");
pReader->Execute(); // does it needed to executed for every path? if no: outside the loop!
}
return True;
}
Also note that, in modern C++ you have smart pointers. Therefore use them, whenever appropriate and avoid manual memory allocations.

What adress does "&ref_var" points to? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Consider the following code:
std::vector &MyClass::getVector() const
{
return (myVec);
}
void aFunc()
{
std::vector *vec = &myClassInstance.getVector();
}
What adress does vec points to? Does it points to the very address of myVec in the myClassInstance object? (btw I know I should return a const ref, but it is an example).
You are returning a reference to myVec in the method getVector. When you take the address of a reference, you get the address of the variable the reference refers to. So vec will contain the address of myVec.
A reference is an alias to another variable. When you return a reference tomyVec from getVector() then you can consider calling the function to be exactly like accessing myVec if it were publicly available.
&MyClass.myVec == &myClassInstance.getVector()
What adress does vec points to?
The address of myClassInstance.getVector() will be the same as the address of myVec.
Also note that since you are returning an lvalue reference you can even use it on the left hand side of an assignment like
myClassInstance.getVector() = some_other_vector;
And now myVec will be a copy of some_other_vector.
Yes, it does point to the very vector myVec in your MyClass instance. See the following sample code:
#include <cstdio>
#include <vector>
class MyClass {
std::vector<int> myVec;
public:
MyClass() {}
~MyClass() {}
std::vector<int>& getVector()
{
return myVec;
}
void printVector() const
{
for(std::vector<int>::const_iterator it = myVec.begin(); it != myVec.end(); ++it)
{
printf("%d ", *it);
}
printf("\n");
}
};
int main(int, char**)
{
MyClass item;
std::vector<int>* vec = &(item.getVector());
vec->push_back(1);
item.printVector();
return 0;
}
Running this program will output:
$ ./a.out
1
So you can see that calling getVector() returns a reference to myVec from the MyClass instance, since we add a new item to the vector (vec->push_back(1)) via the vec pointer then print the MyClass instance's vector, and it shows that the item we added is there in myVec.